package top.huiwow.commands;


import org.bukkit.Bukkit;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import top.huiwow.GameCore;
import top.huiwow.managers.GamePlayerManager;

import java.util.ArrayList;
import java.util.List;

public class UncontrolStatsCommand implements CommandExecutor, TabCompleter {
    GameCore plugin;
    GamePlayerManager gamePlayerManager;
    List<String> groupnames;

    public UncontrolStatsCommand() {
        plugin = GameCore.getInstance();
        gamePlayerManager = plugin.getGamePlayerManager();
    }

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if (sender instanceof ConsoleCommandSender || sender instanceof Player) {
            if (args.length == 1) {

                //this is used to check player stat
                Player p = null;
                try {
                    p = Bukkit.getPlayer(args[0]);
                } catch (Exception e) {
                    //
                }
                if (p == null) {
                    sender.sendMessage("Cannot find the Player!");
                } else {
                    gamePlayerManager.get(p.getUniqueId()).controlledStats=false;
                    sender.sendMessage("success.");
                }
            }else if (sender instanceof Player && args.length == 0) {
                Player player = ((Player) sender);
                gamePlayerManager.get(player.getUniqueId()).controlledStats=false;
                sender.sendMessage("success.");
            } else {
                sender.sendMessage("Invalid usage.Correct usage:\n" +
                        "/uncontrolstats\n" +
                        "/uncontrolstats <player>");
            }
        }

        return true;
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
        if (args.length != 2) return null;

        String arg = args[1];

        if (!isEmptyTab(arg)) {
            return autofill(groupnames, arg);
        }

        return groupnames;
    }

    private boolean isEmptyTab(String s) {
        return s == null || s.equals(" ") || s.isEmpty();
    }

    private List<String> autofill(List<String> groupnames, String input) {
        List<String> list = new ArrayList<>();

        for (String entry : groupnames) {
            if (entry.length() >= input.length()) {
                if (input.equalsIgnoreCase(entry.substring(0, input.length()))) {
                    list.add(entry);
                }
            }
        }

        if (list.isEmpty()) {
            return groupnames;
        }

        return list;
    }
}
